#include "./utils.h"

#include <algorithm>
#include <ctime>
#include <filesystem>  // C++17 引入的文件系统库
#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>

void createDirectoriesIfNeeded(const std::string& filePath) {
  // 使用 C++17 的 <filesystem> 库来获取文件路径的目录部分
  std::filesystem::path dirPath = std::filesystem::path(filePath).parent_path();

  // 如果目录不存在，则创建它
  if (!std::filesystem::exists(dirPath)) {
    if (std::filesystem::create_directories(dirPath)) {
      std::cout << "Created directories: " << dirPath << std::endl;
    } else {
      std::cerr << "Failed to create directories: " << dirPath << std::endl;
    }
  }
}

// 辅助函数：获取当前时间并格式化为字符串
std::string getCurrentTime() {
  std::time_t now = std::time(nullptr);
  char buf[100];
  std::strftime(buf, sizeof(buf), "%Y-%m-%d %H：%M", std::localtime(&now));

  return std::string(buf);
}

// 比较函数，用于std::sort，按照mic_time降序排序
bool compareByMicTimeDesc(const RecordInfo& a, const RecordInfo& b) {
  return a.mic_time > b.mic_time;
}

void recordToFile(const std::vector<RecordInfo>& records, const std::string& outFileName) {
  createDirectoriesIfNeeded(outFileName);

  // 获取当前时间
  std::string currentTime = getCurrentTime();

  // 计算总用时
  double totalTime = 0.0;
  for (const auto& record : records) {
    totalTime += record.mic_time;
  }

  // 打开输出文件
  std::ofstream outFile(outFileName);
  if (!outFile.is_open()) {
    std::cerr << "Failed to open output file: " << outFileName << std::endl;
    return;
  }

  // 写入第一行：日志时间
  outFile << "日志时间： " << currentTime << std::endl;

  // 写入第二行：总用时
  outFile << "总用时： " << std::fixed << std::setprecision(0) << totalTime << " 毫秒" << std::endl;

  // 创建副本并进行排序
  std::vector<RecordInfo> sortedRecords = records;
  std::sort(sortedRecords.begin(), sortedRecords.end(), compareByMicTimeDesc);

  // 遍历排序后的记录，并按照指定格式写入文件
  for (size_t i = 0; i < sortedRecords.size(); ++i) {
    const auto& record = sortedRecords[i];
    double percentage = (record.mic_time / totalTime) * 100.0;
    // outFile << (i + 1) << "\t" << record.name << "\t" << std::fixed << std::setprecision(2) << record.mic_time << "\t" << std::fixed
    //         << std::setprecision(2) << percentage << "%" << std::endl;

    outFile << std::setw(60) << std::left << record.name << "\t" << std::setw(6) << record.mic_time << "\t" << std::setw(10) << std::setprecision(2)
            << std::right << percentage << "%" << std::endl;
  }

  // 关闭文件
  outFile.close();
}

RecordInfoPtrArray makeRecord() {
  return std::make_shared<std::vector<RecordInfo>>();
}